package com.lwp.demo.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author kaka
 */
@Component
@WebFilter(filterName = "serverLoginFilter1",urlPatterns = "/server/*")
public class ServerLoginFilter implements Filter {
    private Logger logger=LoggerFactory.getLogger(ServerLoginFilter.class);
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.debug("Server Filter Activated");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        String systemUrl=req.getParameter("systemUrl");
        logger.info("systemUrl: " + systemUrl);

        if (systemUrl!=null){
            session.setAttribute("systemUrl",systemUrl);
        }
        if (session.getAttribute("systemUrl")!=null){
            systemUrl=session.getAttribute("systemUrl").toString();
            logger.info("get systemUrl: " + systemUrl);
        }

        if (session.getAttribute("isLogin")!=null) {
            if (session.getAttribute("isLogin").equals(true)){
                if(req.getParameter("token")!=null){
                    logger.info("登陆成功");
                    res.sendRedirect(systemUrl+"?token="+req.getParameter("token"));
                    return;
                }
                res.sendRedirect("/main/loginPage");
                return;
            }
            res.sendRedirect("/main/loginPage");
            return;
        }
        //未登陆 跳转登陆
        logger.info("未登陆 跳转登陆");
        res.sendRedirect("/main/loginPage");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {

    }
}
